<template>
  <view class="chatInput" @tap.stop>

    <view class="ipt" :class="{ isIos: isIos }">
      <!-- 语音按钮 -->
      <!-- #ifdef APP-PLUS -->
      <view class="icon">
        <i :class="voiceShow ? 'keyboard' : 'voice'" @tap="voiceShow = !voiceShow"></i>
      </view>
      <!-- #endif -->
      <!-- 输入框 -->

      <view class="textarea-all" v-show="!voiceShow">
        <view class="textarea-container" >
          <textarea :cursor-spacing="20" maxlength="1000" :disable-default-padding="true" confirm-hold hold-keyboard
            auto-blur :focus="inputFocus" v-model="message_content" :style="{ height: textareaHeight }"
            @linechange="handleLineChange" @confirm="sendChatFn(1)" />
        </view>
        <view class="reply" v-if="replyObj">
          <view class="replyText">{{ getNickName(replyObj) }}: {{ typeCopywriting(replyObj) }}</view>
          <image @click="replyObj = null" class="close" src="@/static/image/98.png" mode="widthFix" />
        </view>
      </view>
      <view class="voiceBtn" v-show="voiceShow" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
        按住说话</view>

      <!-- 表情包按钮和操作按钮 -->
      <view class="icon">
        <!-- <view @tap="testFn">test</view> -->
        <i @tap="
          operateShow = false;
        emojiShow = !emojiShow;
        " class="emoji"></i>
        <i @touchstart.prevent="sendChatFn(1)" class="send" v-if="message_content"></i>
        <i @tap="
          emojiShow = false;
        operateShow = !operateShow;
        " class="operate" v-else></i>
      </view>
    </view>
    <emoji :class="{ heightCom: emojiShow }" @update:emojiValue="(e: string) => { message_content += e }" />
    <operate @update:operateValue="uploadImage" :class="{ heightCom: operateShow }" :chatId="chatId" :chatnfo="chatnfo"
      :isGroupChat="isGroupChat" />

    <!-- #ifdef APP-PLUS -->
    <voice @uploadVoice="uploadVoice" ref="voiceRef" :movingDistance="movingDistance" />
    <!-- #endif -->
  </view>
</template>

<script setup lang="ts">
import { ref, computed, getCurrentInstance } from "vue";
import { PersonalSend, GroupSend } from "@/api/ImApi";
import emoji from "./emoji.vue";
import operate from "./operate.vue";
import voice from "./voice.vue";

const emit = defineEmits();
const instance = getCurrentInstance()?.appContext.config.globalProperties;
const props = defineProps({
  chatnfo: {
    type: Object,
    default: () => ({}),
  },
  myUserInfo: {
    type: Object,
    default: () => ({}),
  },
  isGroupChat: {
    type: Boolean,
    default: false,
  },
  baseDataType: {
    type: String,
    default: "singleChat",
  },
  chatId: {
    type: [String],
    default: "",
  },
});
let isIos = ref<boolean>(false);
// #ifdef APP-PLUS
isIos.value = uni.getSystemInfoSync().platform == "ios";
// #endif

// 输入的消息内容
let message_content = ref<string>("");

// 行数
let textareaLineCount = ref<number>(1);

// 最大行数限制
const maxLines = 9;

// 计算动态的 textarea 高度，最大行数为 9
const textareaHeight = computed(() => {
  return Math.min(textareaLineCount.value, maxLines) * 22 + "px"; // 每行 22px
});

// 行数变化时的处理函数
const handleLineChange = (e: any) => {
  textareaLineCount.value = e.detail.lineCount;
};

// 表情包
let emojiShow = ref<boolean>(false);

// 操作栏
let operateShow = ref<boolean>(false);

// 语音
let voiceShow = ref<boolean>(false);

// 关闭弹窗
const closeMask = () => {
  emojiShow.value = false;
  operateShow.value = false;
};

// 引用
let replyObj = ref<any>(null)
const replyFn = (item: any) => {
  console.log(item)
  replyObj.value = item
  inputFocus.value = true

}

// 按住说话
const voiceRef = ref<any>(null);
let startY = ref<number>();
let distanceY = ref<number>();
let movingDistance = ref<number>();
const touchStart = (event: any) => {
  uni.$emit("myCustomEvent", { message: "关闭语音播放" });
  distanceY.value = 0;
  startY.value = event.touches[0].clientY;
  voiceRef.value?.openVoiceFn(true, "open");
};
// 移动
const touchMove = (event: any) => {
  const endY = event.changedTouches[0].clientY;
  if (startY.value) {
    const distanceY = startY.value - endY;
    movingDistance.value = distanceY;
  }
};
// 关闭
const touchEnd = (event: any) => {
  const endY = event.changedTouches[0].clientY;
  if (startY.value) {
    const distanceY = startY.value - endY;
    movingDistance.value = 0;
    if (distanceY > 140) {
      voiceRef.value?.openVoiceFn(false, "close");
      // 取消
    } else {
      voiceRef.value?.openVoiceFn(false, "send");
      // 发送
    }
  }
};

// 上传语音
const uploadVoice = async (item: any) => {
  console.log(item);
  sendChatFn(item.message_type, item);
  // sendChatFn(item.message_type, item);
};

let inputFocus = ref<boolean>(false);
// 上传文件
const uploadImage = async (item: any) => {
  sendChatFn(item.message_type, item);
};

// 创建群聊发送文案
const createGroupSendText = async (text: any) => {
  message_content.value = text;
  sendChatFn(1);
};

// 确认发送 sendStatus  0发送成功 1发送中 2发送失败
// Type=1个人 2群组
// Grade 1普通  2通知
// Grade 1普通
// Cmd 1文字 2图片 3视频  4红包
// Grade 2通知
// Cmd 1心跳包 2发送好友申请 3申请通过
const sendChatFn = async (message_type: number = 1, item: any = {}) => {
  const Time = Date.now();
  let content = message_content.value;
  message_content.value = ''

  if (message_type == 1) {
    // 判断内容是否为空，或者全部是空格和换行符
    if (!content.trim() || /^\s*[\n\r]*$/.test(content)) {
      uni.showToast({
        title: "内容不能为空",
        icon: "none",
      });
      return;
    }
  }

  let Content: string = item?.objectName
    ? item.objectName
    : content.replace(/\n/g, "<br />");

  let chatId = props.chatId;
  let chatObj = {
    // 我自己的id
    myUserId: props.myUserInfo.user_id,
    Sender: props.myUserInfo.user_id,
    // 聊天的用户id
    chatId,
    Cmd: message_type,
    Time,
    Grade: 1,
    Type: props.isGroupChat ? 2 : 1,
    MessageId: null,
    unread: 0,
    Content: {
      Text: Content,
      Url: item.downloadurl,
      Width: item.width,
      Height: item.height,
      Size: item.size,
      FileName: item.file_name,
      Time: item.duration || 0,
    },
  };

  emit("sendChatFn", chatObj);

  // 发送给接口
  let obj: any = {
    message_type,
    message_content: {},
  };
  if (props.isGroupChat) {
    obj["group_id"] = chatId;
    chatObj["Sender"] = props.myUserInfo;
  } else {
    obj["user_id"] = chatId;
  }
  if (replyObj.value) {
    obj["quote_messgae_Id"] = replyObj.value.MessageId;
  }


  if (message_type == 1) {
    obj.message_content = {
      text: content.replace(/\n/g, "<br />"),
    };
  } else {
    obj.message_content = {
      url: item.objectName,
      width: item.width,
      height: item.height,
    };
    if (message_type == 3 || message_type == 4) {
      obj.message_content["time"] = Math.round(item.duration || 0);
    }

    if (message_type == 5) {
      obj.message_content["size"] = item.size;
      obj.message_content["file_name"] = item.file_name;
    }
  }

  let res = props.isGroupChat ? await GroupSend(obj) : await PersonalSend(obj);

  console.log(res);
  // 存入单人聊天数据数据库
  instance?.$db.saveData(props.baseDataType, [
    { ...chatObj, ...res, id: chatId + "_" + res.MessageId },
  ]);

  instance?.$db.saveData("chatList", [
    {
      ...props.chatnfo,
      ...chatObj,
      ...res,
      id: props.isGroupChat ? chatId : Number(chatId),
    },
  ]);

  message_content.value = "";
  replyObj.value = null
};


// 整理Sender
const getSender = (item: any) => {
  return (
    item.myUserId === (props.isGroupChat ? item.Sender.user_id : item.Sender)
  );
};
const getNickName = (item: any) => {
  let boo = getSender(item);
  return boo
    ? props.myUserInfo.nick_name
    : props.isGroupChat
      ? item.Sender.nick_name
      : props.chatnfo.nick_name;
};

const testFn = () => {
  let i = 0;
  setInterval(() => {
    message_content.value = "测试数据=" + i++;
    sendChatFn(1);
    console.log(message_content.value);
  }, 1000);
};

defineExpose({
  closeMask,
  createGroupSendText,
  replyFn
});
</script>

<style scoped lang="scss">
@import "../../../static/scss/chat.scss";
</style>
